<template>
  <div id="read">
    <head-view></head-view>
    <div class="container" @click="func1()">
      <div class="content">
        <ul>
          <li>{{ passage[0].Title }}</li>
          <li>{{ passage[0].author }}</li>
        </ul>
        <span
          v-for="(item, index) in text1"
          :key="index"
          @click.stop="func($event, index)"
          :style="{ color: index == t ? 'red' : '' }"
        >
          {{ item }}
        </span>
      </div>
    </div>

    <div
      class="box"
      v-show="isShow"
      :style="{ left: sleft + 'px', top: stop + 'px' }"
    >
      {{ trans }}
    </div>
  </div>
</template>

<script>
import api from "@/fetch/api";
export default {
  name: "read",
  data() {
    return {
      trans: "暂无翻译",
      passage: [{ Title: "", author: "", content: "" }],
      t: -1,
      text1: [],
      sleft: 0,
      stop: 0,
      isShow: false,
    };
  },
  mounted() {
    api.getMessage().then(
      (res) => {
        console.log("开始请求接口");
        switch (res.code) {
          case "200":
            //将获取的词库储存进data中
            this.passage = res.data;
            this.text1 = this.passage[0].content.split(" ");
            console.log(this.text1);
            break;
          case "401":
            console.log("err401");
            this.err = true;
            break;
        }
      },
      (err) => {
        console.log(err);
      }
    );
  },
  methods: {
    func(e, i) {
      this.t = i;
      this.sleft = e.clientX;
      this.stop = e.clientY;
      this.isShow = true;
      var word = e.currentTarget.innerHTML;
      word = word.replace(/(^\s*)|(\s*$)/g, "");
      api.transWord(word).then(
        (res) => {
          switch (res.code) {
            case "200":
              this.trans = res.data[0].translation;
              break;
            case "401":
              console.log("err401");
              this.err = true;
              break;
          }
        },
        (err) => {
          console.log(err);
        }
      );
    },
    func1() {
      this.t = -1;
      this.isShow = false;
    },
  },
};
</script>

<style scoped>
.box {
  position: absolute;
  width: 100px;
  height: 100px;
  border: 1px solid yellowgreen;
  background-color: yellowgreen;
}
.container {
  width: 84vw;
  height: 90vh;
  margin: 0 auto;
  font-family: "Times New Roman", Times, serif;
  background-color: rgb(148, 155, 155);
}
.content {
  margin: 1vh 1vw 1vh 1vw;
}
.container ul li:nth-of-type(1),
li:nth-of-type(2) {
  text-align: center;
  padding-top: 6px;
}
</style>